
package at.fhj.ase.crypto.server;

import org.slf4j.Logger;

import at.fhj.ase.crypto.common.util.LogUtil;
import at.fhj.ase.crypto.common.util.StringUtil;
import at.fhj.ase.crypto.server.net.ClientManager;

/**
 * Class only responsible for
 * <ul>
 * <li>parsing the application arguments and<br>
 * <li>starting the application via {@link Server#main(String[])}-method.
 * </ul>
 * The argument(s) to that method should be a valid port number, which means > 1023 ("well known ports").<br>
 * If the arguments are not correct, a small usage is printed and the program exits with error-code <code>1</code>.
 * 
 * @author sfe | www.fh-joanneum.at | Practical Aspects of Cryptography
 */
public class Server extends Thread {
  private static final Logger logger = LogUtil.getLogger();

  /**
   * Starting point of the server application.
   * 
   * @param args the application arguments which should be the single port number (> 1023)
   */
  public static void main(String args[]) {
    if (args.length != 1) {
      logger.error("Invalid arguments, usage:\n" + printUsage());
      System.exit(1);
    }

    final int PORT = Integer.parseInt(StringUtil.checkLength(args[0], 1, 5));
    new Server(PORT);
  }

  /** @return a small application usage information if it has been called with wrong arguments */
  private static String printUsage() {
    return "secureChatFedlServer <PORT>";
  }

  /**
   * Constructor (private, called by main-method) responsible for really starting the application and catching all {@link Throwable}s.<br>
   * If a {@link Throwable} is caught, the application will exit with error-code <code>1</code>.
   * 
   * @param port the port number this server should be started with (> 1023)
   */
  private Server(final int port) {
    try {
      ClientManager.getInstance(port).start();
    } catch (Throwable t) {
      logger.error("Server not startable, exiting with error code 1...", t);
      System.exit(1);
    }
  }
}
